package dao.impl;

import bean.UserBean;
import dao.IUserDAO;

import java.sql.SQLException;

public class UserDAOImpl extends BaseDAO implements IUserDAO {
    @Override
    public UserBean login(String username, String pwd) {
        this.setConnection();
        String sql = "select * from t_user where u_name=? and u_password=?";
        UserBean userBean = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, username);
            ps.setObject(2, pwd);
            rs = ps.executeQuery();
            if (rs.next()) {
                userBean = getUser();

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return userBean;
    }

    @Override
    public void update(int id, double money) {
        this.setConnection();
        String sql = "update t_user set u_money=? where u_id=?";
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, money);
            ps.setObject(2, id);
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public UserBean getUserById(int id) {
        this.setConnection();
        UserBean userBean = null;
        String sql = "select * from t_user where u_id=?";
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, id);
            rs = ps.executeQuery();
            while (rs.next()) {
                userBean = getUser();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userBean;
    }

    @Override
    public UserBean getUserName(String name) {
        this.setConnection();
        UserBean userBean = null;
        String sql = "select * from t_user where u_name=?";
        try {
            ps = con.prepareStatement(sql);
            ps.setObject(1, name);
            rs = ps.executeQuery();
            while (rs.next()) {
                userBean = getUser();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userBean;
    }
    private UserBean getUser() throws SQLException {
        UserBean user = new UserBean();
        user.setId(rs.getInt("u_id"));
        user.setName(rs.getString("u_name"));
        user.setPwd(rs.getString("u_password"));
        user.setMoney(rs.getDouble("u_money"));
        return user;
    }
}
